<template>
	<a-modal title="发货" :width="1500" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading"
		okText="确认发货" @ok="handleSubmit" @cancel="handleCancel">
		<a-card :bordered="false">
			<a-form :form="form">
				<a-form-item label="发货单号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
					<a-input v-decorator="['orderNumber', { rules: [{ required: true, message: '请输入发货单号！' }] }]" />
				</a-form-item>
				<a-form-item label="发货备注" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
					<a-input placeholder="请输入" v-decorator="['remark', { rules: [{ required: true, message: '请输入发货备注！' }] }]" />
				</a-form-item>
				<a-form-item label="发货方式" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
					<a-input placeholder="请输入" v-decorator="['delivery', { rules: [{ required: true, message: '请输入发货方式！' }] }]" />
				</a-form-item>
				<a-form-item label="发货凭证" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
					<a-input v-decorator="['file', { rules: [{ required: true, message: '请输入发货凭证！' }] }]" v-show="false" />
					<FcUpload :file-list="fileList" @change="(value) => form.setFieldsValue({ file: value })" />
				</a-form-item>

			</a-form>

			<!-- <s-table
        ref="table"
        size="default"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.code"
        :rowSelection="null"
        :showPagination="false"
      >

        <template slot="thisCompleteNumber" slot-scope="text, record">
          <a-input-number v-model:value="record.thisCompleteNumber" :step="1"
                          :min="0"
                          :max="record.number - record.deliveredNumber" style="width: 67px;"
                          :disabled="record.number - record.deliveredNumber <= 0"/>
        </template>

<template slot="storehousePositionRemark" slot-scope="text, record">
          <a-input v-model:value="record.material.storehousePositionRemark"/>
        </template>

</s-table> -->
			<a-form-item>
				<a-radio-group button-style="solid" v-model="btnValue">
					<a-radio-button v-for="item in typeList" :key="item.value" :value="item.value">{{
						item.label
					}}
					</a-radio-button>
				</a-radio-group>
				<a-button size="default" style="margin-left: 40px;" @click="handleAddMaterial(
					btnValue == typeList[1].value ? listByMaterial.map(item => item.materialId)
						: btnValue == typeList[2].value ? listByCable.map(item => item.materialId)
							: btnValue == typeList[3].value ? listByPacking.map(item => item.materialId)
								: []
				)" icon="plus" type="danger" :disabled="btnValue == typeList[0].value">新增
				</a-button>
				<!-- 22--{{ filteredData }} -->
				<a-table ref="table" size="default" style="margin-bottom: 24px"
					:columns="btnValue == typeList[0].value ? columnsProduct : columnsOther" :data-source="btnValue == typeList[0].value ? tableData
						: btnValue == typeList[1].value ? listByMaterial
							: btnValue == typeList[2].value ? listByCable
								: btnValue == typeList[3].value ? listByPacking
									: []" :pagination="false">
					<template slot="remark" slot-scope="text, record">
						<a-input v-model:value="record.remark" />
					</template>

					<template slot="thisCompleteNumber" slot-scope="text, record">
						<a-input-number v-model:value="record.thisCompleteNumber" :step="1" :min="0"
							:max="record.number - record.deliveredNumber" :disabled="record.number - record.deliveredNumber <= 0" />
					</template>

					<template slot="storehousePositionRemark" slot-scope="text, record">
						<a-input v-model:value="record.storehousePositionRemark" />
					</template>
					<!-- 发货数量（原料线缆包材） -->
					<template slot="number" slot-scope="text, record">
						<a-input-number :min="0" :max="record.inventoryNumber" style="width: 100%" placeholder="请输入发货数量"
							v-model:value="record.number" />
						<!-- <a-input v-model:value="record.storehousePositionRemark"/> -->
					</template>
					<!-- 本次发货箱数 -->
					<template slot="deliveredBoxNumber" slot-scope="text, record">
						<a-input-number :min="0" :disabled="record.inStoreNumber - record.deliveredNumber == 0"
							@change="deliveredBoxNumberChange" :max="record.dfhNumber" style="width: 100%" placeholder="请输入"
							v-model:value="record.deliveredBoxNumber" />
					</template>

					<template slot="action" slot-scope="text, record, index">
						<a @click="handleTableDelete(record, index)">删除</a>
					</template>

					<template slot="materialType" slot-scope="text, record, index">
						<span style="font-weight: bold;" :style="{
							color:
								record.materialType == '1473944069297156097' ? '#139ff0' :
									record.materialType == '1473944389062504450' ? '#33dd33' :
										record.materialType == '1473944715475824641' ? '#fc6d18' :
											record.materialType == '1473944318434619394' ? '#f04450' :
												'--'
						}">{{
							record.materialType == '1473944069297156097' ? '原料' :
								record.materialType == '1473944389062504450' ? '线缆' :
									record.materialType == '1473944715475824641' ? '包材' :
										record.materialType == '1473944318434619394' ? '成品' :
											'--'
						}}</span>
					</template>

				</a-table>
			</a-form-item>
		</a-card>
		<select-material :typeList="typeList" @selected="handleSelected" ref="selectMaterialRef" />
	</a-modal>
</template>

<script>
import { STable } from '@/components'
import { page } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import { handleProductionOrderDoDeliver } from '@/api/modular/main/emsorder/emsOrderManage'
import FcUpload from '@/components/FCUpload/FcUpload'
import SelectMaterial from './selectMaterial'

export default {

	components: {
		FcUpload,
		STable,
		SelectMaterial
	},

	data: function () {
		return {
			btnValue: '1473944318434619394',  //表格筛选按钮，默认成品
			typeList: [
				// {label:'全部', value:''},
				{ label: '成品', value: '1473944318434619394' },
				{ label: '原料', value: '1473944069297156097' },
				{ label: '线缆', value: '1473944389062504450' },
				{ label: '包材', value: '1473944715475824641' },
			],
			listByMaterial: [],  //原料列表数据
			listByCable: [], //线缆列表数据
			listByPacking: [], //包材列表数据
			orderMaterials: [],
			orgIdSupplier: 'all',
			tableData: [],


			labelCol: {
				xs: { span: 24 },
				sm: { span: 3 }
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 18 }
			},
			form: this.$form.createForm(this),
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			// columns: [
			//   {
			//     title: '产品编号',
			//     dataIndex: 'materialCode'
			//   },
			//   {
			//     title: '产品名称',
			//     dataIndex: 'materialName'
			//   },
			//   {
			//     title: '总数量',
			//     dataIndex: 'number',
			//   },
			//   {
			//     title: '已发货数量',
			//     dataIndex: 'deliveredNumber',
			//   },
			//   {
			//     title: '待发货数量',
			//     dataIndex: '',
			//     customRender: (text, record, index) => `${record.number - record.deliveredNumber}`
			//   },
			//   {
			//     title: '本次发货数量',
			//     dataIndex: '',
			//     scopedSlots: {customRender: 'thisCompleteNumber'}
			//   },
			//   {
			//     title: '库位备注',
			//     dataIndex: '',
			//     scopedSlots: {customRender: 'storehousePositionRemark'}
			//   },
			// ],
			columnsProduct: [       // 成品
				{
					title: '序号', width: '80px',
					dataIndex: 'index',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '物料',
					dataIndex: 'materialName'
				},
				{
					title: '物料类型',
					dataIndex: 'materialType',
					scopedSlots: { customRender: 'materialType' },
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '备注',
					dataIndex: '',
					scopedSlots: { customRender: 'remark' }
				},
				{
					title: '库位备注',
					dataIndex: '',
					scopedSlots: { customRender: 'storehousePositionRemark' }
				},
				// {
				//   title: '发货数量',
				//   dataIndex: 'number'
				// },
				{
					title: '待发货数量',
					dataIndex: 'inStoreNumber',
					customRender: (text, record, index) => record.inStoreNumber - record.deliveredNumber

				},
				{
					title: '本次发货数量',
					dataIndex: '',
					scopedSlots: { customRender: 'thisCompleteNumber' }
				},
				{
					title: '待发货箱数',
					dataIndex: 'dfhNumber',
					// customRender: (text, record, index) => {
					// 	let newRecord = JSON.parse(JSON.stringify(record));
					// 	return newRecord.inStoreBoxNumber - newRecord.deliveredBoxNumber
					// }
				},
				{
					title: '本次发货箱数',
					dataIndex: 'deliveredBoxNumber',
					scopedSlots: { customRender: 'deliveredBoxNumber' }
				},
				// {
				//   title: '操作',
				//   dataIndex: '',
				// 	scopedSlots: {customRender: 'action'}
				// },
			],
			columnsOther: [       // 原料、线缆、包材
				{
					title: '序号', width: '80px',
					dataIndex: 'index',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '物料名称',
					dataIndex: 'materialName'
				},
				{
					title: '物料类型',
					dataIndex: 'materialType',
					scopedSlots: { customRender: 'materialType' },
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '发货数量',
					dataIndex: 'number',
					scopedSlots: { customRender: 'number' }
				},
				{
					title: '库存',
					dataIndex: 'inventoryNumber',
				},
				{
					title: '备注',
					dataIndex: 'remark',
				},
				{
					title: '操作',
					dataIndex: '',
					scopedSlots: { customRender: 'action' }
				},
			],
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			visible: false,
			confirmLoading: false,
			emsOrder: null,
			viewState: '',
			extra: {},
			fileList: [],
		}
	},
	computed: {
		// filteredData() {
		// let orgIdSupplier = this.orgIdSupplier
		// if (orgIdSupplier == 'all') {
		//   return this.orderMaterials
		// }
		// let filteredData
		// if (orgIdSupplier == 'other') {
		//   let dictValues = this.supplierList.map(dict => dict.id)
		//   filteredData = this.orderMaterials.filter(value => {
		//     return dictValues.findIndex(value1 => value1 == value.orgIdSupplier) == -1
		//   })
		// } else {
		//   filteredData = this.orderMaterials.filter(value => {
		//     return value.orgIdSupplier == orgIdSupplier
		//   })
		// }
		// return filteredData
		// return this.loadData()
		// },
		// supplierList() {
		//   return this.$util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id, this.$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id])
		// }
	},
	methods: {
		deliveredBoxNumberChange(e) {
			console.log(e);

		},
		// 加载数据方法 必须为 Promise 对象
		getList() {
			page({ pageNo: 1, ...this.queryParam }).then((res) => {
				res.data.rows.forEach(value => {
					value.thisCompleteNumber = 0
				})
				this.tableData = res.data.rows.map(val => {
					return {
						...val,
						deliveredBoxNumber: 0,
						dfhNumber: val.inStoreBoxNumber - val.deliveredBoxNumber
					}
				}) || []
			})
		},
		handleTableDelete(row, index) {
			if (this.btnValue == this.typeList[0].value) {
				this.filteredData.splice(index, 1)
			} else if (this.btnValue == this.typeList[1].value) {
				this.listByMaterial.splice(index, 1)
			} else if (this.btnValue == this.typeList[2].value) {
				this.listByCable.splice(index, 1)
			} else if (this.btnValue == this.typeList[3].value) {
				this.listByPacking.splice(index, 1)
			}

		},
		// 新增物料
		handleAddMaterial(arr) {
			let selectList = arr
			this.$refs.selectMaterialRef.init(selectList, this.btnValue, '')
		},
		// 选择物料完成
		handleSelected(obj) {
			if (obj.materialType == this.typeList[1].value) {
				this.listByMaterial.push(obj)
			} else if (obj.materialType == this.typeList[2].value) {
				this.listByCable.push(obj)
			} else if (obj.materialType == this.typeList[3].value) {
				this.listByPacking.push(obj)
			}
		},
		// add(record) {
		//   if (!(record.selectedRows && record.selectedRows.length > 0)) {
		//     this.$message.error('请先选择物料!')
		//     return
		//   }
		//   this.visible = true
		//   // 设定订单类型
		//   setTimeout(() => {
		//     this.form.setFieldsValue(record)
		//     this.createOrderNumber()
		//   }, 100)
		//   // 创建简单订单(无单出入库)时,record中包含选择的物料
		//   this.orderMaterials.length = 0
		//   this.orderMaterials.push(...record.selectedRows)
		// },


		show(record) {
			this.visible = true
			this.emsOrder = record
			this.queryParam = {}
			this.queryParam.orderId = record.orderId
			this.queryParam.materialType = this.$businessEnum.MATERIAL_TYPE_ENUM.product.id
			this.queryParam.pageSize = -1
			this.getList()  //获取表格数据

			setTimeout(() => {
				this.form.resetFields()
				// this.form.setFieldsValue(record)
				this.createOrderNumber()
				this.fileList = []
				// this.handleOk()
				// this.$refs.table.clearSelected()

			}, 100)
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		// handleOk() {
		//   this.$refs.table.refresh()
		// },
		// 打开弹框时候生成一个单号
		createOrderNumber() {
			var d = new Date()
			var year = d.getFullYear()
			var month = d.getMonth()
			month = month + 1 > 12 ? 1 : month + 1
			month = month > 9 ? month : "0" + month.toString()
			var day = d.getDate()
			day = day > 9 ? day : "0" + day.toString()
			var hour = d.getHours()
			hour = hour > 9 ? hour : "0" + hour.toString()
			var minute = d.getMinutes()
			minute = minute > 9 ? minute : "0" + minute.toString()
			var second = d.getSeconds()
			second = second > 9 ? second : "0" + second.toString()

			let num = parseInt(Math.random() * 100000).toString()
			// 如果随机数长度不够5位,则在后面补0,够5位为止
			for (let i = num.length; i < 5; i++) {
				num += '0'
			}

			// let header = this.type==this.ORDER_TYPE_ENUM.inOrder.id?'WDRK': this.type==this.ORDER_TYPE_ENUM.outOrder.id?'WDCK': this.type==this.ORDER_TYPE_ENUM.purchaseOrder.id?'CG':''

			let scOrderNo = 'FH' + year + month + day + hour + minute + second + num

			this.form.setFieldsValue({ orderNumber: scOrderNo })
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		handleSubmit() {
			const { form: { validateFields } } = this
			this.confirmLoading = true


			let errMaterial = this.listByMaterial.some(item => !item.number || item.number == 0 || item.number > item.inventoryNumber)
			let errCable = this.listByCable.some(item => !item.number || item.number == 0 || item.number > item.inventoryNumber)
			let errPacking = this.listByPacking.some(item => !item.number || item.number == 0 || item.number > item.inventoryNumber)
			console.log('@@@@@@@@@@@', errMaterial || errCable || errPacking)
			if (errMaterial || errCable || errPacking) {
				this.confirmLoading = false
				return this.$message.error('发货数量不能为空 且 不能为0 且 不能大于库存!')
			}


			// let rows = this.$refs.table.localDataSource
			validateFields((errors, values) => {
				if (!errors) {


					// 将池中的物料记录转成订单物料记录
					let orderMaterials = this.tableData
						.map(item => {
							// let {
							//   storehousePositionRemark,
							//   thisCompleteNumber,
							//   materialPoolId,
							//   materialId,
							//   number,
							//   poolType,
							//   materialType,
							//   remark,
							//   status,
							//   createTime,
							//   createUser,
							//   updateTime,
							//   updateUser
							// } = values
							return {
								// materialId,
								// number,
								// remark,
								// materialPoolId, //物料池ID，创建后删除用
								// storehousePositionRemark,
								...item,
								number: item.thisCompleteNumber
							}
						})
					let listByMaterial = this.listByMaterial.map(values => {
						let { materialPoolId, materialId, number, remark } = values
						return {
							materialId,
							number,
							remark,
							materialPoolId, //物料池ID，创建后删除用
						}
					})
					let listByCable = this.listByCable.map(values => {
						let { materialPoolId, materialId, number, remark } = values
						return {
							materialId,
							number,
							remark,
							materialPoolId, //物料池ID，创建后删除用
						}
					})
					let listByPacking = this.listByPacking.map(values => {
						let { materialPoolId, materialId, number, remark } = values
						return {
							materialId,
							number,
							remark,
							materialPoolId, //物料池ID，创建后删除用
						}
					})


					// values = Object.assign(
					//   values,
					//   {orderId: this.emsOrder.orderId, orderMaterials},
					// )
					values = {
						...values,
						orderMaterials: [...orderMaterials, ...listByMaterial, ...listByCable, ...listByPacking],
						orderId: this.emsOrder.orderId,
					}
					handleProductionOrderDoDeliver(values).then((res) => {
						this.confirmLoading = false
						if (res.success) {
							this.$message.success('编辑成功')
							this.handleCancel()
							this.$emit('ok', values)
						} else {
							this.$message.info('编辑失败：' + res.message)
						}
					}).finally((res) => {
						this.confirmLoading = false
					})
				} else {
					this.confirmLoading = false
				}
			})
		},
		handleCancel() {
			// this.$refs.table.refresh();
			this.form.resetFields();
			this.tableData = []
			this.visible = false
			this.listByMaterial = []
			this.listByCable = []
			this.listByPacking = []
			this.fileList = []
			this.btnValue = this.typeList[0].value
		},
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}
</style>
